package hu.bme.aut.consulttime.server.entityservices;

import hu.bme.aut.consulttime.client.UserService;
import hu.bme.aut.consulttime.entitydtos.UserDTO;
import hu.bme.aut.consulttime.server.entities.User;
import jBCrypt.BCrypt;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {

	private static final long serialVersionUID = -4418575071157515676L;

	public static final EntityManager entityManager() {
		return EntityManagerFactoryWrapper.get().createEntityManager();
	}

	@Override
	public String retrieveUserRole() {

		
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            
        if (authentication==null){
        	System.out.println("Not logged in");
            return null;
        }
		
        return authentication.getAuthorities().iterator().next().toString();

	} 
	
	@Override
	public UserDTO retrieveUserData() {
		EntityManager em = entityManager();
		User user = null;

		
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            
        if (authentication==null){
        	System.out.println("Not logged in");
            return null;
        }
		
		try {
			TypedQuery<User> query = em.createQuery(
					"select user from User user where user.userName = ?1",
					User.class);
			query.setParameter(1, authentication.getPrincipal());
			user = query.getSingleResult();
		
		} catch (Throwable t) {
				t.printStackTrace();
		} finally {
			if (em != null) {
				em.close();
			}
		}
		
		if (user != null) {
			return createUserDTO(user);
		} else {
			return null;
		}
	} 
	
	public Boolean updateUser(UserDTO userDTO) {
		EntityManager em = entityManager();
		try {
			em.getTransaction().begin();
			User user = em.find(User.class, userDTO.getUserId());

			user.setUserName(userDTO.getUserName());
			user.setEmail(userDTO.getEmail());
			user.setEmailNotification(userDTO.isEmailNotification());
			user.setFirstName(userDTO.getFirstName());
			user.setLastName(userDTO.getLastName());
			
			if(userDTO.getPassword() != null){
				// Password hash
				String passwordHash = BCrypt.hashpw(userDTO.getPassword(),
						BCrypt.gensalt());
				user.setPassword(passwordHash);
			}
			
			em.getTransaction().commit();
		} finally {
			em.close();
		}
		return true;
	}
	
	private UserDTO createUserDTO(User user) {
		return new UserDTO(user.getUserId(), user.getUserName(), user.getFirstName(), user.getLastName(), user.getEmail(), user.isEmailNotification());
	}
}
